package com.zbf.ocr;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author: LCG
 * @date: 2023-02-05 11:40:52
 * @description:
 **/
public class TestOCR {
    public static void main(String[] args) throws IOException, TesseractException {

        File file=new File("C:\\Users\\lenovo\\Desktop\\01.png");
        BufferedImage img = ImageIO.read(file);
        String s = doOCR(img);
    }

    // 入参：图片流
    public static String doOCR(BufferedImage image) throws TesseractException, IOException {
        String path="E:/tessdata";
        //String path = resource.getURL().getPath();
        //创建Tesseract对象
        ITesseract tesseract = new Tesseract();
        //设置中文字体库路径
        tesseract.setDatapath(path);
        //中文识别
        tesseract.setLanguage("chi_sim");
        //执行ocr识别
        String result = tesseract.doOCR(image);

        String[] split = result.split("\\n");

        for (String s : split) {
            System.out.println("******->"+s);
            if(s.startsWith("订")){
                String orderNo = s.substring(6,29);
                System.out.println("订单编号："+orderNo);
                String createTime0 = s.split("成交时间:")[1].substring(0,16);
                String c0 = createTime0.split(" ")[1];
                String c1 = createTime0.split(" ")[2].substring(0, 2);
                String c2 = createTime0.split(" ")[2].substring(2, 4);
                String createTime=c0+" "+c1+":"+c2;
                System.out.println("成交时间："+createTime);
            }

        }

        //替换回车和tal键  使结果为一行
        //result = result.replaceAll("\\r|\\n", "-").replaceAll(" ", "");
        return result;
    }
}
